﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGinnBPM.Services;
using System.IO;

namespace NGinnBPM.Services.Utilities
{
    /// <summary>
    /// Persistent counter? WTF?
    /// Used for round-robin scheduling etc
    /// </summary>
    public class PersistentCounters : IPersistentCounters
    {
        public string BaseDirectory { get; set; }
        #region IPersistentCounters Members

        public int Increment(string counterId)
        {
            if (!Directory.Exists(BaseDirectory)) Directory.CreateDirectory(BaseDirectory);
            lock (this)
            {
                int cnt = 0;
                string pth = Path.Combine(BaseDirectory, counterId + ".count");
                using (FileStream fs = new FileStream(pth, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    StreamReader sr = new StreamReader(fs);
                    string s = sr.ReadToEnd();
                    if (s != null && s.Length > 0)
                    {
                        Int32.TryParse(s, out cnt);
                    }
                    fs.Seek(0, SeekOrigin.Begin);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(cnt + 1);
                    sw.Flush();
                }
                return cnt;
            }
        }

        #endregion
    }
}
